package com.mantru.iotpot.Begin;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.Dialog.ManufacturerDialog;
import com.mantru.iotpot.Home.ErrorActivity;
import com.mantru.iotpot.Home.HomeActivity;
import com.mantru.iotpot.R;
import com.mantru.iotpot.Util.ToastUtils;
import com.mantru.iotpot.eventbus.EventMessage;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;


public class BeginSetActivity extends AppCompatActivity {

    ProgressBar progressBar;
    TextView progressBarText;
    private Handler handler; // 用于定时检查的 Handler
    private ApplicationClass ac;
    private long startTime; // 用于记录自检开始的时间
    private Button retryButton; // 用于超时显示的按钮
    private Button button;
    private ProgressBar progressBar2;
    private ImageView manufacturerButton;
    private Handler handlerButton = null;
    private Runnable runnable = null;
    private long pressDuration = 5000L;
    private ManufacturerDialog manufacturerDialog = null;
    private int timeout = 120 * 1000; // 设置超时时间为30秒（可以根据需要调整）
    private String TAG = "BeginSetActivity";

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {//点击登录之后跳转到这个activity中
        super.onCreate(savedInstanceState);
        ac = ((ApplicationClass)getApplication());

        // 初始化 Handler
        handler = new Handler();

    }

    //eventbus解注册
    @Override
    protected void onDestroy() {
        ac.Device_Stop_0x00E0();
        // 移除所有定时任务，避免内存泄漏
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    // 处理接收到的事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventBusMessage(EventMessage event) {
        // 检查消息ID是否是初始化进度的消息
        if (event.id == EventMessage.MSG_ID_InitProgress) {
            try {
                JSONObject json = new JSONObject(event.message);
//                Log.d("BeginSetActivity","json: " + json);
                int progress = json.getInt("progress");
                progressBar.setProgress(progress);// 更新ProgressBar的进度
                progressBarText.setText(progress + "%");// 更新进度文本
                if (progress == 100) {// 判断进度是否达到100%
                    // 跳转到activity_main3
//                    startActivity(new Intent(this, HomeActivity.class));
                    startActivity(new Intent(this, BeginSetActivity.class));
//                    // 可选：关闭当前活动
//                    finish();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }else if (event.id == EventMessage.MSG_ID_ErrorInfo) {//收到故障之后
            try {
                // 解析 JSON 数据
                JSONObject json = new JSONObject(event.message);
                String errorCode = json.getString("error_code");
                String errorDesc = json.getString("error_desc");
                Log.d(TAG, "Error Code: " + errorCode);
                Log.d(TAG, "Error Desc: " + errorDesc);
                Intent intent = new Intent(this, ErrorActivity.class);
                intent.putExtra("error_code",errorCode);
                intent.putExtra("error_desc",errorDesc);
                startActivity(intent);
                // 根据 needCode 做其他处理
            } catch (JSONException e) {
                Log.e(TAG, "Error parsing JSON: " + e.getMessage());
                ac.SaveLog("解析故障消息出错，错误原因：" + e.getMessage());
            }
        }
    }


    // 修改 startCheckingSelfStatus 方法
    private void startCheckingSelfStatus() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                Log.d("BeginSetActivity", "CheckSelfStatus: " + ac.CheckSelfStatus);
                long elapsedTime = System.currentTimeMillis() - startTime; // 计算已过去的时间
                Log.d("BeginSetActivity", "elapsedTime: " + elapsedTime);
                if (ac.CheckSelfStatus == 1) {
                    if (elapsedTime >= timeout) { // 如果超时
//                        ac.CheckSelfStatus = 3; // 设置自检状态为失败
                        //Toast.makeText(BeginSetActivity.this, "自检超时", Toast.LENGTH_SHORT).show();
                        ToastUtils.show(BeginSetActivity.this, "自检超时");
                        progressBar2.setVisibility(View.GONE);
                        retryButton.setVisibility(View.VISIBLE);
                        retryButton.setOnClickListener(v -> {
//                            ac.CheckSelfStatus = 0; // 重置自检状态
                            startActivity(new Intent(BeginSetActivity.this, ManualCheakActivity.class));
                            finish();
                        });
                    } else {
                        handler.postDelayed(this, 500);
                    }
                } else if (ac.CheckSelfStatus == 2) {//进入首页
                    startActivity(new Intent(BeginSetActivity.this, HomeActivity.class));
                    finish();
                } else if (ac.CheckSelfStatus == 3) {//自检失败重新跳转回登陆界面
                    //Toast.makeText(BeginSetActivity.this, "自检失败", Toast.LENGTH_SHORT).show();
                    ToastUtils.show(BeginSetActivity.this, "自检失败");
                    startActivity(new Intent(BeginSetActivity.this, ManualCheakActivity.class));
                    Log.d("BeginSetActivity", "自检失败，已跳转回主界面");
                } else if (ac.CheckSelfStatus == 4) {
                    startActivity(new Intent(BeginSetActivity.this, ManualCheakActivity.class));
                }
            }
        }, 500);
    }

    @Override
    protected void onResume(){
        super.onResume();
        int DeviceStatus = ac.DeviceStatus;
        Log.d("BeginSetActivity","DeviceStatus: " + DeviceStatus);
        int CheckSelfStatus = ac.CheckSelfStatus;
        if (DeviceStatus == 0){//设备未初始化
            setContentView(R.layout.activity_main4);//加载加载界面（加载条）
            // 初始化ProgressBar和进度文本
            progressBar = findViewById(R.id.progressbar);
            progressBarText = findViewById(R.id.progressbar_text);
            EventBus.getDefault().register(this);//注册EventBus
        } else if (DeviceStatus == 1) {//进入自检
            setContentView(R.layout.activity_main3);//进入自检界面
            manufacturerButton = findViewById(R.id.manufacturer_set_button);
            button = findViewById(R.id.button2);
            //设置厂家设置跳转
            manufacturerButton.setOnLongClickListener(v -> {
                handlerButton = new Handler(Looper.getMainLooper());
                runnable = () -> {
                    if ( manufacturerDialog == null || !manufacturerDialog.isShowing() ){
                        manufacturerDialog = new ManufacturerDialog(BeginSetActivity.this, R.style.Common_Dialog);
                        manufacturerDialog.setManufacturerDialogListener(() -> {
                            Intent intent = new Intent(BeginSetActivity.this, ManufacturerSetActivity.class);
                            startActivity(intent);
                        });
                        manufacturerDialog.show();
                    }
                };
                handlerButton.postDelayed(runnable, pressDuration);
                return true;
            });
            manufacturerButton.setOnTouchListener((v, event) -> {
                if ( event.getAction() == MotionEvent.ACTION_UP ){
                    if ( handlerButton != null && runnable != null ){
                        handlerButton.removeCallbacks(runnable);
                    }
                }
                return false;
            });
            //打转菊花
            progressBar2 = findViewById(R.id.progressBar2);
            retryButton = findViewById(R.id.retry_button);
            if (CheckSelfStatus == 0){//代表未开始自检
                button.setVisibility(View.VISIBLE);//显示“开始自检”按钮
                button.setOnClickListener(v -> {
                    button.setVisibility(View.GONE);// 隐藏按钮，不占布局空间
                    progressBar2.setVisibility(View.VISIBLE);// 显示进度条
                    retryButton.setVisibility(View.GONE);
                    ac.Device_SendCommand_0x00E0();//开始自检
                    startTime = System.currentTimeMillis(); // 记录自检开始时间
                    Log.d("BeginSetActivity","startTime: " + startTime);
                    startCheckingSelfStatus();
                });
            } else if (CheckSelfStatus == 1) {//代表正在自检中
                startCheckingSelfStatus();
            } else if (CheckSelfStatus == 2) {//代表已完成自检
                startActivity(new Intent(this, HomeActivity.class));//进入首页
            } else if (CheckSelfStatus == 3) {//代表自检过程中发现故障
                //Toast.makeText(BeginSetActivity.this,"自检失败",Toast.LENGTH_SHORT).show();
                ToastUtils.show(BeginSetActivity.this,"自检失败");
                startActivity(new Intent(BeginSetActivity.this, ManualCheakActivity.class));
            } else if (CheckSelfStatus == 4) {
                startActivity(new Intent(BeginSetActivity.this, ManualCheakActivity.class));
            }

        } else if (DeviceStatus == 2) {//表示自检完成
            startActivity(new Intent(BeginSetActivity.this,HomeActivity.class));
        }
    }

}